//
//  APIConnection.m
//  Bracelet
//
//  Created by betta on 2/13/15.
//  Copyright (c) 2015 jing zhao. All rights reserved.
//



#import "APIConnection.h"

#import <AFNetworking/AFNetworking.h>

static APIConnection * _instance;

@implementation APIConnection
+ (APIConnection *) shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[APIConnection alloc] init];
    });
    
    return _instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        // timeout set
        [AFHTTPRequestOperationManager manager].requestSerializer.timeoutInterval = API_TIMEOUT;
        [AFHTTPRequestOperationManager manager].requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    }
    return self;
}

+(id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}

#pragma mark - PRIVATE -


#pragma mark - PUBLIC -

- (void) get:(NSString *)url
        data:(NSDictionary *)data
    netError:(Error)netError
   apiFinish:(APIFinish)apiFinish {
    NSString *requestPath = [API_HOST stringByAppendingPathComponent:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager]
                                         GET:requestPath
                                         parameters:data
                                         success:^(AFHTTPRequestOperation *operation,
                                                   id responseObject) {
                                             NSLog(@"GET: %@\nresponse: %@", requestPath, responseObject);
                                             apiFinish(responseObject);
                                         } failure:^(AFHTTPRequestOperation *operation,
                                                     NSError *error) {
                                             NSLog(@"GET: %@\nerror: %@", requestPath, error);
                                             netError(error);
                                         }];
    [operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection,
                                                            NSCachedURLResponse *cachedResponse) {
        NSLog(@"GET: %@\ncache: %@", requestPath, cachedResponse);
        return cachedResponse;
    }];
    NSLog(@"GET: %@\ndata: %@", requestPath, data);
}

- (void) post:(NSString *)url
         data:(NSDictionary *)data
     netError:(Error)netError
    apiFinish:(APIFinish)apiFinish {
    NSString *requestPath = [API_HOST stringByAppendingPathComponent:url];
    [[AFHTTPRequestOperationManager manager] POST:[API_HOST stringByAppendingPathComponent:url]
                                       parameters:data
                                          success:^(AFHTTPRequestOperation *operation,
                                                    id responseObject) {
                                              NSLog(@"POST: %@\nresponse: %@", requestPath, responseObject);
                                              apiFinish(responseObject);
                                          } failure:^(AFHTTPRequestOperation *operation,
                                                      NSError *error) {
                                              NSLog(@"POST: %@\nerror: %@", requestPath, error);
                                              netError(error);
                                          }];
    NSLog(@"POST: %@\ndata: %@", requestPath, data);
}


- (void) post:(NSString *)url
         data:(NSDictionary *)data
       header:(NSDictionary*)headerData
    netError:(Error)netError
    apiFinish:(APIFinish)apiFinish {
    
    NSString *requestPath = [API_HOST stringByAppendingPathComponent:url];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [headerData enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [manger.requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
    [manger POST:[API_HOST stringByAppendingPathComponent:url]
                                   parameters:data
                                      success:^(AFHTTPRequestOperation *operation,
                                                id responseObject) {
                                          NSLog(@"POST: %@\nresponse: %@", requestPath, responseObject);
                                          apiFinish(responseObject);
                                      } failure:^(AFHTTPRequestOperation *operation,
                                                  NSError *error) {
                                          NSLog(@"POST: %@\nerror: %@", requestPath, error);
                                          netError(error);
                                      }];
}

@end
